package com.kevin.util;

import cn.hutool.core.date.TimeInterval;
import cn.hutool.core.thread.SyncFinisher;

import java.util.Random;

/**
 * kevin<br/>
 * 2021/1/15 23:34<br/>
 */

public class BenchmarkTest {

    private final SyncFinisher sf;
    private final TimeInterval timeInterval;
    private long interval;

    public BenchmarkTest(int threadSize) {
        this.sf = new SyncFinisher(threadSize);
        this.timeInterval = new TimeInterval();
    }

    /**
     * 执行测试
     *
     * @param runnable 要测试的内容
     * @return this
     */
    public BenchmarkTest test(Runnable runnable) {
        timeInterval.start();
        this.sf//
                .addRepeatWorker(runnable)//
                .setBeginAtSameTime(true)// 同时开始
                .start();

        this.interval = timeInterval.interval();
        return this;
    }

    /**
     * 获取执行时间
     *
     * @return 执行时间，单位毫秒
     */
    public long getInterval() {
        return this.interval;
    }

    public static void main(String[] args) {
        BenchmarkTest benchmark = new BenchmarkTest(2000);
        benchmark.test(() -> {
            System.out.println(genarateVersionNo("20210102", true));
        });
    }

    private static final Random RANDOM = new Random();

    public static int genarateVersionNo(String docId, Boolean majorUpdate) {
        int lastVersionNo = 100;
        try {
            Thread.sleep(RANDOM.nextInt(2000));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if (majorUpdate == null) {
            majorUpdate = false;
        }
        return majorUpdate ? calculateMajor(lastVersionNo) : lastVersionNo + 1;
    }

    private static int calculateMajor(int lastVersionNo) {
        String strVersion = String.valueOf(lastVersionNo);
        strVersion = strVersion.substring(0, strVersion.length() - 2);
        return (Integer.parseInt(strVersion) + 1) * 100;
    }
}
